package b1w1nn1ng.crossf1t.business;

import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

public class HistoryStack {
	static ArrayList<String> stack = new ArrayList<String>();
		
	/**
	 * Helper method--gets the last item from the stack. If the
	 * stack is empty, adds the current page to the stack and adds
	 * that instead (should only happen when we're at the home page,
	 * effectively disabling the back button when we're at that
	 * screen.
	 * 
	 * @param request The servletRequest containing page info.
	 * @return String representation of the URL of the last visited
	 *  page
	 */
	public static String peek() {		
		if(stack.size() == 0)
			return null;
		return stack.get(stack.size()-1);
	}
	
	/**
	 * This function is called whenever we hit a new page. It is
	 * responsible for figuring out if the new page should be pushed
	 * onto the list, and doing so.
	 * 
	 * @param request The servletRequest containing page info.
	 */
	public static void push(HttpServletRequest request) {
		String currURL = request.getRequestURI();
		if(!currURL.equals(peek())) {
			stack.add(request.getRequestURI());
		}
		return;
	}
	
	/**
	 * Returns the last page visited. This is NOT the last item on
	 * the stack--that is the current page: thus, this function
	 * removes the last 2 items from the stack when used and returns
	 * the second to last one. If the does not contain more than one
	 * entry (we're on the home page) then pop returns that entry and
	 * does not remove it.
	 * @return The last page visited.
	 */
	public static String pop () {
		if(stack.size() == 1)
			return HistoryStack.peek();
		stack.remove(stack.size()-1);
		return HistoryStack.peek();
	}
}
